using System.Collections.ObjectModel;
using System.Text;

namespace RadioTimer.Services
{
    /// <summary>
    /// 日志条目类
    /// </summary>
    public class LogEntry
    {
        public DateTime Timestamp { get; set; }
        public string Message { get; set; } = string.Empty;
        public string Level { get; set; } = "Info";
    }

    /// <summary>
    /// 日志服务接口
    /// </summary>
    public interface ILogService
    {
        ObservableCollection<LogEntry> LogEntries { get; }
        void Log(string message, string level = "Info");
        void ClearLogs();
    }

    /// <summary>
    /// 日志服务实现类
    /// </summary>
    public class LogService : ILogService
    {
        private readonly object _lock = new object();
        private readonly int _maxLogEntries = 1000;

        public ObservableCollection<LogEntry> LogEntries { get; } = new ObservableCollection<LogEntry>();

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="message">日志消息</param>
        /// <param name="level">日志级别</param>
        public void Log(string message, string level = "Info")
        {
            lock (_lock)
            {
                var logEntry = new LogEntry
                {
                    Timestamp = DateTime.Now,
                    Message = message,
                    Level = level
                };

                // 在主线程上更新UI
                MainThread.BeginInvokeOnMainThread(() =>
                {
                    LogEntries.Add(logEntry);

                    // 限制日志条目数量，避免内存问题
                    if (LogEntries.Count > _maxLogEntries)
                    {
                        LogEntries.RemoveAt(0);
                    }
                });
            }
        }

        /// <summary>
        /// 清除所有日志
        /// </summary>
        public void ClearLogs()
        {
            lock (_lock)
            {
                MainThread.BeginInvokeOnMainThread(() =>
                {
                    LogEntries.Clear();
                });
            }
        }
    }
}